<template>
  <el-card>
    <el-form ref="addForm" label-width="120px" :model="formData" :rules="formRules">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item prop="first_cateid" label="一级分类">
            <el-select v-model="formData.first_cateid" @change="getSecondCates">
              <el-option value label="请选择"></el-option>
              <el-option
                v-for="item in catesList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="second_cateid" label="二级分类">
            <el-select v-model="formData.second_cateid">
              <el-option value label="请选择"></el-option>
              <el-option
                v-for="item in secondCates"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="goodsname" label="商品名称">
            <el-input v-model="formData.goodsname" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item prop="price" label="商品价格">
            <el-input v-model="formData.price" placeholder="请输入商品价格"></el-input>
          </el-form-item>
          <el-form-item prop="market_price" label="市场价格">
            <el-input v-model="formData.market_price" placeholder="请输入市场价格"></el-input>
          </el-form-item>
          <el-form-item prop="img" label="商品图片">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :auto-upload="false"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="fileChange"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item prop="specsid" label="商品规格">
            <el-select v-model="formData.specsid" @change="specsChange">
              <el-option value label="请选择"></el-option>
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :label="item.specsname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="specsattr" label="规格属性值">
            <el-select v-model="formData.specsattr" multiple>
              <el-option v-if="specsAttrValues.length==0" value label="请选择"></el-option>
              <el-option
                v-else
                v-for="(item,index) in specsAttrValues"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isnew" label="是否新品">
            <el-radio-group v-model="formData.isnew">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="ishot" label="是否热卖">
            <el-radio-group v-model="formData.ishot">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="status" label="状态">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="second">
          <vue-wangeditor id="editor" ref="wangeditor" v-model="formData.description"></vue-wangeditor>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" @click="submitForm('addForm')">立即添加</el-button>
        <el-button @click="resetForm('addForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 导入wangEditor
import vueWangeditor from 'vue-wangeditor'
export default {
  components: {
    vueWangeditor
  },
  data() {
    return {
      formData: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        specsid: "",
        specsattr: [],
        isnew: 0,
        ishot: 0,
        status: 1,
        description:''
      },
      // 表单校验规则
      formRules: {
        first_cateid: {
          required: true,
          message: "请选择一级分类",
          trigger: "blur"
        },
        second_cateid: {
          required: true,
          message: "请选择二级分类",
          trigger: "blur"
        },
        goodsname: {
          required: true,
          message: "请输入商品名称",
          trigger: "blur"
        },
        price: { required: true, message: "请输入商品价格", trigger: "blur" },
        market_price: {
          required: true,
          message: "请输入市场价格",
          trigger: "blur"
        },
        ishot: { required: true, message: "请选择", trigger: "blur" },
        isnew: { required: true, message: "请选择", trigger: "blur" },
        status: { required: true, message: "请选择商品状态", trigger: "blur" },
        specsid: { required: true, message: "请选择商品规格", trigger: "blur" },
        specsattr: {
          required: true,
          message: "请选择规格属性值",
          trigger: "blur"
        }
      },
      // 默认显示的tab栏
      activeName: "first",
      // 图片上传组件控制属性
      dialogImageUrl: "",
      dialogVisible: false,
      // 商品分类数组
      catesList: [],
      // 二级分类数组
      secondCates: [],
      // 规格列表
      specsList: [],
      // 规格可选值
      specsAttrValues: []
    };
  },
  methods: {
    // tab栏切换回调函数
    handleClick() {},
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片数量超出限制回调函数
    limitTips() {
      this.$error("最多只能上传一张图片");
    },
    // 监听图片修改
    fileChange(file){
      this.formData.img=file.raw;
    },
    // 获取商品分类
    async getCates() {
      const res = await this.$http.get("/api/catelist?istree=1");
      this.catesList = res.list;
    },
    // 根据一级分类获取二级分类
    getSecondCates(id) {
      if (isNaN(id)) {
        return false;
      }
      const index = this.catesList.findIndex(item => item.id == id);
      this.secondCates = this.catesList[index].children;
    },
    // 监听规格更新
    async specsChange(id) {
      if (isNaN(id)) {
        return false;
      }
      // 清空之前已选择的规格属性值
      this.formData.specsattr=[];
      // 获取规格信息
      const res = await this.$http.get(`/api/specsinfo?id=${id}`);
      if (res.code == 200) {
        this.specsAttrValues = res.list[0].attrs;
      }
    },
    // 获取商品规格
    async getSpecs() {
      const res = await this.$http.get("/api/specslist");
      this.specsList = res.list;
    },
    // 提交表单
    submitForm(form) {
      this.$refs[form].validate(async valid => {
        if (valid) {
          const fd=new FormData();
          for(let key in this.formData){
            fd.append(key,this.formData[key]);
          }
          // 获取富文本内容
          fd.append('description',this.$refs.wangeditor.getHtml());
          const res=await this.$http.post('/api/goodsadd',fd);
          if(res.code==200){
            this.$success('操作成功');
          }else{
            this.$error('操作失败');
          }
        } else {
          console.log("表单校验不通过");
        }
      });
    }
  },
  created() {
    this.getCates();
    this.getSpecs();
  }
};
</script>
<style>
</style>